package logic

import (
	"box-fresh-serv/modles/cache"
	"box-fresh-serv/modles/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"box-fresh-serv/box_fresh_servrpc/box_fresh_servrpc"
	"box-fresh-serv/box_fresh_servrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *box_fresh_servrpc.GoodsListRequest) (*box_fresh_servrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line

	var goods mysql.Goods

	var lists []*box_fresh_servrpc.GoodsList

	key := fmt.Sprintf("goodsList+%s", in)
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if result == "" {
		var err error
		lists, err = goods.GoodsLists(mysql.DB, lists, in)
		if err != nil {
			return nil, err
		}

		marshal, _ := json.Marshal(lists)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*30)

	} else {
		json.Unmarshal([]byte(result), &lists)
	}

	return &box_fresh_servrpc.GoodsListResponse{
		List: lists,
	}, nil
}
